package org.example.curriculum_design_6_16.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.curriculum_design_6_16.entity.pojo.*;
import org.example.curriculum_design_6_16.entity.vo.CompetitionParticipationVo;
import org.example.curriculum_design_6_16.entity.vo.IntellectualPropertyVo;
import org.example.curriculum_design_6_16.entity.vo.Result;
import org.example.curriculum_design_6_16.entity.vo.ScholarshipRankingVo;
import org.example.curriculum_design_6_16.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/scholarship")
public class ScholarshipController {
    
    @Autowired
    private ScholarshipCandidateService scholarshipCandidateService;
    
    @Autowired
    private ScholarshipRuleService scholarshipRuleService;
    
    @Autowired
    private CompetitionParticipationService competitionParticipationService;
    
    @Autowired
    private ResearchPaperService researchPaperService;
    
    @Autowired
    private IntellectualPropertyService intellectualPropertyService;
    
    @Autowired
    private PoliticalPerformanceService politicalPerformanceService;
    
    @Autowired
    private SocialServiceService socialServiceService;

    // ==================== 奖学金候选人管理 ====================
    
    /**
     * 获取所有奖学金候选人（所有学生自动参加评选）
     */
    @GetMapping("/candidates")
    public Result<List<ScholarshipCandidate>> getAllCandidates() {
        try {
            List<ScholarshipCandidate> candidates = scholarshipCandidateService.list();
            // 去重逻辑：studentId+scholarshipType+applicationYear唯一，优先保留有排名的记录
            Map<String, ScholarshipCandidate> uniqueMap = new HashMap<>();
            for (ScholarshipCandidate c : candidates) {
                if (c.getScholarshipType() == null || c.getScholarshipType().trim().isEmpty()) {
                    continue;
                }
                String formattedYear = formatApplicationYear(c.getApplicationYear());
                c.setApplicationYear(formattedYear);
                String key = c.getStudentId() + "_" + c.getScholarshipType() + "_" + c.getApplicationYear();
                if (!uniqueMap.containsKey(key)) {
                    uniqueMap.put(key, c);
                } else {
                    ScholarshipCandidate existing = uniqueMap.get(key);
                    boolean shouldReplace = false;
                    if (c.getRanking() != null && existing.getRanking() == null) {
                        shouldReplace = true;
                    } else if (c.getRanking() == null && existing.getRanking() != null) {
                        shouldReplace = false;
                    } else if (c.getRanking() != null && existing.getRanking() != null) {
                        shouldReplace = c.getRanking() < existing.getRanking();
                    } else {
                        double cScore = c.getTotalScore() != null ? c.getTotalScore() : 0;
                        double existingScore = existing.getTotalScore() != null ? existing.getTotalScore() : 0;
                        shouldReplace = cScore > existingScore;
                    }
                    if (shouldReplace) {
                        uniqueMap.put(key, c);
                    }
                }
            }
            List<ScholarshipCandidate> uniqueList = new ArrayList<>(uniqueMap.values());
            return Result.success(uniqueList);
        } catch (Exception e) {
            log.error("获取奖学金候选人失败", e);
            return Result.error(500, "获取奖学金候选人失败: " + e.getMessage());
        }
    }
    
    /**
     * 格式化申请学年
     */
    private String formatApplicationYear(String year) {
        if (year == null || year.trim().isEmpty()) {
            return year;
        }
        
        // 如果已经是xxxx-xxxx格式，直接返回
        if (year.contains("-")) {
            return year;
        }
        
        // 如果是xxxx格式，转换为xxxx-(xxxx+1)格式
        try {
            int yearNum = Integer.parseInt(year.trim());
            return yearNum + "-" + (yearNum + 1);
        } catch (NumberFormatException e) {
            return year; // 如果无法解析，返回原值
        }
    }

    /**
     * 根据学生ID获取奖学金评选记录
     */
    @GetMapping("/candidates/student/{studentId}")
    public Result<List<ScholarshipCandidate>> getCandidatesByStudentId(@PathVariable String studentId) {
        try {
            List<ScholarshipCandidate> candidates = scholarshipCandidateService.list(
                scholarshipCandidateService.lambdaQuery().eq(ScholarshipCandidate::getStudentId, studentId)
            );
            return Result.success(candidates);
        } catch (Exception e) {
            log.error("获取学生奖学金评选记录失败", e);
            return Result.error(500, "获取学生奖学金评选记录失败: " + e.getMessage());
        }
    }

    // ==================== 奖学金规则管理 ====================
    
    /**
     * 获取所有奖学金规则
     */
    @GetMapping("/rules")
    public Result<List<ScholarshipRule>> getAllRules() {
        try {
            List<ScholarshipRule> rules = scholarshipRuleService.list();
            return Result.success(rules);
        } catch (Exception e) {
            log.error("获取奖学金规则失败", e);
            return Result.error(500, "获取奖学金规则失败: " + e.getMessage());
        }
    }

    /**
     * 添加奖学金规则
     */
    @PostMapping("/rules")
    public Result<Boolean> addRule(@RequestBody ScholarshipRule rule) {
        try {
            boolean success = scholarshipRuleService.save(rule);
            if (success) {
                return Result.success(true);
            }
            return Result.error(500, "添加奖学金规则失败");
        } catch (Exception e) {
            log.error("添加奖学金规则失败", e);
            return Result.error(500, "添加奖学金规则失败: " + e.getMessage());
        }
    }

    /**
     * 更新奖学金规则
     */
    @PutMapping("/rules/{id}")
    public Result<Boolean> updateRule(@PathVariable Integer id, @RequestBody ScholarshipRule rule) {
        try {
            rule.setId(id);
            boolean success = scholarshipRuleService.updateById(rule);
            if (success) {
                return Result.success(true);
            }
            return Result.error(500, "更新奖学金规则失败");
        } catch (Exception e) {
            log.error("更新奖学金规则失败", e);
            return Result.error(500, "更新奖学金规则失败: " + e.getMessage());
        }
    }

    /**
     * 删除奖学金规则
     */
    @DeleteMapping("/rules/{id}")
    public Result<Boolean> deleteRule(@PathVariable Integer id) {
        try {
            boolean success = scholarshipRuleService.removeById(id);
            if (success) {
                return Result.success(true);
            }
            return Result.error(500, "删除奖学金规则失败");
        } catch (Exception e) {
            log.error("删除奖学金规则失败", e);
            return Result.error(500, "删除奖学金规则失败: " + e.getMessage());
        }
    }

    // ==================== 学科竞赛相关 ====================
    
    /**
     * 获取学生学科竞赛记录
     */
    @GetMapping("/competition/student/{studentId}")
    public Result getStudentCompetitions(@PathVariable String studentId) {
        try {
            return Result.success(competitionParticipationService.getParticipationsByStudentId(studentId));
        } catch (Exception e) {
            log.error("获取学生学科竞赛记录失败", e);
            return Result.error(500, "获取学生学科竞赛记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取学生指定学年学科竞赛记录
     */
    @GetMapping("/competition/student/{studentId}/year/{academicYear}")
    public Result getStudentCompetitionsByYear(
            @PathVariable String studentId,
            @PathVariable String academicYear) {
        try {
            return Result.success(competitionParticipationService.getParticipationsByStudentIdAndYear(studentId, academicYear));
        } catch (Exception e) {
            log.error("获取学生学年学科竞赛记录失败", e);
            return Result.error(500, "获取学生学年学科竞赛记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加学科竞赛记录
     */
    @PostMapping("/competition")
    public Result addCompetition(@RequestBody CompetitionParticipation participation) {
        try {
            return Result.success(competitionParticipationService.addParticipation(participation));
        } catch (Exception e) {
            log.error("添加学科竞赛记录失败", e);
            return Result.error(500, "添加学科竞赛记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新学科竞赛记录
     */
    @PutMapping("/competition")
    public Result updateCompetition(@RequestBody CompetitionParticipation participation) {
        try {
            return Result.success(competitionParticipationService.updateParticipation(participation));
        } catch (Exception e) {
            log.error("更新学科竞赛记录失败", e);
            return Result.error(500, "更新学科竞赛记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除学科竞赛记录
     */
    @DeleteMapping("/competition/{id}")
    public Result deleteCompetition(@PathVariable Integer id) {
        try {
            return Result.success(competitionParticipationService.deleteParticipation(id));
        } catch (Exception e) {
            log.error("删除学科竞赛记录失败", e);
            return Result.error(500, "删除学科竞赛记录失败: " + e.getMessage());
        }
    }

    // ==================== 学术论文相关 ====================
    
    /**
     * 获取学生学术论文记录
     */
    @GetMapping("/paper/student/{studentId}")
    public Result getStudentPapers(@PathVariable String studentId) {
        try {
            return Result.success(researchPaperService.getResearchPapersByStudentId(studentId));
        } catch (Exception e) {
            log.error("获取学生学术论文记录失败", e);
            return Result.error(500, "获取学生学术论文记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加学术论文记录
     */
    @PostMapping("/paper")
    public Result addPaper(@RequestBody ResearchPaper paper) {
        try {
            return Result.success(researchPaperService.addResearchPaper(paper));
        } catch (Exception e) {
            log.error("添加学术论文记录失败", e);
            return Result.error(500, "添加学术论文记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新学术论文记录
     */
    @PutMapping("/paper")
    public Result updatePaper(@RequestBody ResearchPaper paper) {
        try {
            return Result.success(researchPaperService.updateResearchPaper(paper));
        } catch (Exception e) {
            log.error("更新学术论文记录失败", e);
            return Result.error(500, "更新学术论文记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除学术论文记录
     */
    @DeleteMapping("/paper/{id}")
    public Result deletePaper(@PathVariable Integer id) {
        try {
            return Result.success(researchPaperService.deleteResearchPaper(id));
        } catch (Exception e) {
            log.error("删除学术论文记录失败", e);
            return Result.error(500, "删除学术论文记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取学生论文总分
     */
    @GetMapping("/paper/totalScore/{studentId}")
    public Result getPaperTotalScore(@PathVariable String studentId) {
        try {
            return Result.success(researchPaperService.getTotalPaperScore(studentId));
        } catch (Exception e) {
            log.error("获取学生论文总分失败", e);
            return Result.error(500, "获取学生论文总分失败: " + e.getMessage());
        }
    }

    // ==================== 知识产权相关 ====================
    
    /**
     * 获取学生知识产权记录
     */
    @GetMapping("/intellectual/student/{studentId}")
    public Result getStudentIntellectualProperties(@PathVariable String studentId) {
        try {
            return Result.success(intellectualPropertyService.getIntellectualPropertiesByStudentId(studentId));
        } catch (Exception e) {
            log.error("获取学生知识产权记录失败", e);
            return Result.error(500, "获取学生知识产权记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加知识产权记录
     */
    @PostMapping("/intellectual")
    public Result addIntellectualProperty(@RequestBody IntellectualProperty intellectualProperty) {
        try {
            return Result.success(intellectualPropertyService.addIntellectualProperty(intellectualProperty));
        } catch (Exception e) {
            log.error("添加知识产权记录失败", e);
            return Result.error(500, "添加知识产权记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新知识产权记录
     */
    @PutMapping("/intellectual")
    public Result updateIntellectualProperty(@RequestBody IntellectualProperty intellectualProperty) {
        try {
            return Result.success(intellectualPropertyService.updateIntellectualProperty(intellectualProperty));
        } catch (Exception e) {
            log.error("更新知识产权记录失败", e);
            return Result.error(500, "更新知识产权记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除知识产权记录
     */
    @DeleteMapping("/intellectual/{id}")
    public Result deleteIntellectualProperty(@PathVariable Integer id) {
        try {
            return Result.success(intellectualPropertyService.deleteIntellectualProperty(id));
        } catch (Exception e) {
            log.error("删除知识产权记录失败", e);
            return Result.error(500, "删除知识产权记录失败: " + e.getMessage());
        }
    }

    // ==================== 思政成绩相关 ====================
    
    /**
     * 获取学生思政成绩
     */
    @GetMapping("/political/student/{studentId}")
    public Result getStudentPoliticalScore(@PathVariable String studentId) {
        try {
            return politicalPerformanceService.selectByStudentId(studentId) != null ? 
                Result.success(politicalPerformanceService.selectByStudentId(studentId)) : 
                Result.fail(404, "未找到该学生的思政成绩记录");
        } catch (Exception e) {
            log.error("获取学生思政成绩失败", e);
            return Result.error(500, "获取学生思政成绩失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新学生思政成绩
     */
    @PutMapping("/political/score")
    public Result updatePoliticalScore(
            @RequestParam String studentId,
            @RequestParam double newScore) {
        try {
            int result = politicalPerformanceService.updateScore(studentId, newScore);
            return result > 0 ? Result.success(result, "更新思政成绩成功") : Result.fail(404, "更新思政成绩失败");
        } catch (Exception e) {
            log.error("更新学生思政成绩失败", e);
            return Result.error(500, "更新学生思政成绩失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查学生基础分是否为零
     */
    @GetMapping("/political/check-base-score")
    public Result checkBaseScore(@RequestParam String studentId) {
        try {
            boolean result = politicalPerformanceService.isBaseScoreZeroInSemester(studentId);
            return Result.success(result);
        } catch (Exception e) {
            log.error("检查学生基础分失败", e);
            return Result.error(500, "检查学生基础分失败: " + e.getMessage());
        }
    }

    // ==================== 综合计算 ====================
    
    /**
     * 计算学生奖学金总分
     */
    @GetMapping("/calculate/{studentId}")
    public Result<Map<String, Object>> calculateTotalScore(@PathVariable String studentId, @RequestParam String academicYear) {
        double totalScore;
        double competitionScore;
        double researchScore;
        double politicalScore;
        double intellectualScore;
        double serviceScore;
        Map<String, Object> result;
        try {
            result = new HashMap<>();
            result.put("studentId", studentId);
            result.put("academicYear", academicYear);

            // 计算各项分数
            totalScore = 0.0;
            double academicScore = 0.0;
            politicalScore = 0.0;
            researchScore = 0.0;
            serviceScore = 0.0;
            competitionScore = 0.0;
            intellectualScore = 0.0;

            // 1. 获取思政成绩（按学年）
            PoliticalPerformance political = politicalPerformanceService.selectByStudentId(studentId, academicYear);
            if (political != null) {
                politicalScore = political.getTotalScore() != null ? political.getTotalScore() : 0.0;
                totalScore += politicalScore;
            }

            // 2. 获取学术论文总分（按学年）
            Double paperResult = researchPaperService.getTotalPaperScore(studentId, academicYear);
            researchScore = paperResult;
            totalScore += researchScore;

            // 3. 获取学科竞赛总分（按学年）
            competitionScore = competitionParticipationService.getSum(studentId, academicYear);
            totalScore += competitionScore;

            // 4. 获取知识产权总分（按学年）
            Double intellectualResult = intellectualPropertyService.getTotalScore(studentId, academicYear);
            intellectualScore = intellectualResult != null ? intellectualResult : 0.0;
            totalScore += intellectualScore;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

        // 5. 获取社会服务总分（按学年）
        double serviceResult = socialServiceService.calculateTotalSocialScore(studentId, academicYear);
        serviceScore = serviceResult;
        totalScore += serviceResult;

        // 设置结果
        result.put("totalScore", Math.round(totalScore * 100.0) / 100.0);
        result.put("politicalScore", Math.round(politicalScore * 100.0) / 100.0);
        result.put("researchScore", Math.round(researchScore * 100.0) / 100.0);
        result.put("competitionScore", Math.round(competitionScore * 100.0) / 100.0);
        result.put("intellectualScore", Math.round(intellectualScore * 100.0) / 100.0);
        result.put("serviceScore", Math.round(serviceScore * 100.0) / 100.0);

        return Result.success(result);
    }

    // ==================== 奖学金排名相关 ====================
    
    /**
     * 计算指定年级的奖学金排名
     */
    @PostMapping("/ranking/calculate/{grade}")
    public Result calculateScholarshipRanking(
            @PathVariable Integer grade,
            @RequestParam String academicYear,
            @RequestParam String scholarshipType) {
        try {
            if (grade != 2 && grade != 3) {
                return Result.fail(400, "年级参数错误，只能是2(研二)或3(研三)");
            }
            
            scholarshipCandidateService.calculateScholarshipRanking(grade, academicYear, scholarshipType);
            return Result.success("计算排名成功");
        } catch (Exception e) {
            log.error("计算奖学金排名失败", e);
            return Result.error(500, "计算奖学金排名失败: " + e.getMessage());
        }
    }

    /**
     * 计算所有年级的奖学金排名
     */
    @PostMapping("/ranking/calculate/all")
    public Result calculateAllScholarshipRankings(
            @RequestParam String academicYear,
            @RequestParam String scholarshipType) {
        try {
            scholarshipCandidateService.calculateAllScholarshipRankings(academicYear, scholarshipType);
            return Result.success("计算所有年级排名成功");
        } catch (Exception e) {
            log.error("计算所有年级奖学金排名失败", e);
            return Result.error(500, "计算所有年级奖学金排名失败: " + e.getMessage());
        }
    }

    /**
     * 获取指定年级的奖学金排名
     */
    @GetMapping("/ranking/{grade}")
    public Result getScholarshipRanking(
            @PathVariable Integer grade,
            @RequestParam String academicYear,
            @RequestParam String scholarshipType) {
        try {
            if (grade != 2 && grade != 3) {
                return Result.fail(400, "年级参数错误，只能是2(研二)或3(研三)");
            }
            
            List<ScholarshipRankingVo> rankings = scholarshipCandidateService.getScholarshipRanking(grade, academicYear, scholarshipType);
            return Result.success(rankings);
        } catch (Exception e) {
            log.error("获取奖学金排名失败", e);
            return Result.error(500, "获取奖学金排名失败: " + e.getMessage());
        }
    }

    /**
     * 获取学生的奖学金排名
     */
    @GetMapping("/ranking/student/{studentId}")
    public Result getStudentRanking(
            @PathVariable String studentId,
            @RequestParam String academicYear,
            @RequestParam String scholarshipType) {
        try {
            ScholarshipCandidate ranking = scholarshipCandidateService.getStudentRanking(studentId, academicYear, scholarshipType);
            if (ranking == null) {
                return Result.fail(404, "未找到该学生的排名记录");
            }
            return Result.success(ranking);
        } catch (Exception e) {
            log.error("获取学生排名失败", e);
            return Result.error(500, "获取学生排名失败: " + e.getMessage());
        }
    }

    /**
     * 获取排名统计信息
     */
    @GetMapping("/ranking/statistics")
    public Result getRankingStatistics(
            @RequestParam String academicYear,
            @RequestParam String scholarshipType) {
        try {
            Map<String, Object> statistics = scholarshipCandidateService.getRankingStatistics(academicYear, scholarshipType);
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取排名统计信息失败", e);
            return Result.error(500, "获取排名统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 批量更新奖学金结果
     */
    @PutMapping("/ranking/update-results")
    public Result updateScholarshipResults(
            @RequestParam String academicYear,
            @RequestParam String scholarshipType,
            @RequestParam Integer grade,
            @RequestParam Integer topCount) {
        try {
            if (grade != 2 && grade != 3) {
                return Result.fail(400, "年级参数错误，只能是2(研二)或3(研三)");
            }
            
            // 获取排名列表
            List<ScholarshipRankingVo> rankings = scholarshipCandidateService.getScholarshipRanking(grade, academicYear, scholarshipType);
            
            // 更新前topCount名的结果为"获奖"
            for (int i = 0; i < Math.min(topCount, rankings.size()); i++) {
                ScholarshipRankingVo ranking = rankings.get(i);
                ScholarshipCandidate candidate = new ScholarshipCandidate();
                candidate.setStudentId(ranking.getStudentId());
                candidate.setScholarshipType(scholarshipType);
                candidate.setApplicationYear(academicYear);
                candidate.setFinalResult("获奖");
                
                // 更新或插入记录
                scholarshipCandidateService.saveOrUpdate(candidate);
            }
            
            return Result.success("更新奖学金结果成功");
        } catch (Exception e) {
            log.error("更新奖学金结果失败", e);
            return Result.error(500, "更新奖学金结果失败: " + e.getMessage());
        }
    }
}
